package charlie.shop.warehouse;

import com.charlie.beans.Product;
import com.charlie.sessions.ProductFacadeLocal;
import java.io.IOException;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Edit selected product servlet
 * 
 * @author Gleb
 */
@WebServlet(name = "editProductServlet", urlPatterns = {"/warehouse/editProductServlet"})
public class editProductServlet extends HttpServlet {

    @EJB
    private ProductFacadeLocal productFacade;

    /**
     * Get product id, set products description;
     * get product parameters, edit product.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        if (request.getParameter("productName") == null || request.getParameter("productName").equals("")) {
            if (request.getParameter("id") != null) {
                Product product = productFacade.find(Integer.valueOf(request.getParameter("id")));
                request.setAttribute("product", product);
                getServletContext().getRequestDispatcher("/warehouse/editProduct.jsp").forward(request, response);
            }
        } else {
            if (request.getParameter("productName") != null && !request.getParameter("productName").equals("") && request.getParameter("cost") != null && !request.getParameter("cost").equals("")) {
                Product product = productFacade.find(Integer.valueOf(request.getParameter("id")));
                product.setName(request.getParameter("productName"));
                product.setCost(Integer.parseInt(request.getParameter("cost")));
                product.setDescription(request.getParameter("description"));
                product.setImage(request.getParameter("upFile"));
                productFacade.edit(product);
                response.sendRedirect(request.getContextPath() + "/warehouse/products");
                return;
            }
        }       
    }
}
